package com.atguigu.flink.chapter10.function;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

/**
 * @Author lzc
 * @Date 2023/6/30 09:08
 */
public class AggFunctionDemo {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        tEnv.executeSql("create table sensor(" +
                            " id string, " +
                            " ts bigint, " +
                            " vc int " +
                            ")with(" +
                            "  'connector' = 'kafka', " +
                            "  'topic' = 's1', " +
                            "  'properties.bootstrap.servers' = 'hadoop162:9092', " +
                            "  'properties.group.id' = 'atguigu', " +
                            "  'scan.startup.mode' = 'latest-offset', " +
                            "  'format' = 'csv' " +
                            ")");
        
        Table table = tEnv.from("sensor");
        
        // 把字符变成大写的功能
        
        // 1. 注册一个自定义函数
        tEnv.createTemporaryFunction("my_avg", MyAvg.class);
        // 2. 在Table api 中使用
        /*table
            .groupBy($("id"))
            *//*.aggregate(call("my_avg", $("vc")).as("vc_a"))
            .select($("id"), $("vc_a"))*//*
            .select($("id"), call("my_avg", $("vc")).as("vc_a"))
            .execute()
            .print();*/
        
        
        // 3. 在 sql 中使用
        tEnv.sqlQuery("select id, my_avg(vc) ma from sensor group by id").execute().print();
        
        
    }
    
    public static class MyAvg extends AggregateFunction<Double, SumCount> {
        
        @Override
        public Double getValue(SumCount acc) {
            return acc.sum * 1.0 / acc.count;
        }
        
        // 初始化累计器
        @Override
        public SumCount createAccumulator() {
            return new SumCount(0, 0L);
        }
        
        // 方法名必须是: accumulate
        // 参数列表: 第一个必须是: 累加起
        // 第二... 根据实际
        public void accumulate(SumCount acc, Integer vc) {
            acc.sum += vc;
            acc.count++;
        }
    }
    
    public static class SumCount {
        public Integer sum;
        public Long count;
        
        public SumCount(Integer sum, Long count) {
            this.sum = sum;
            this.count = count;
        }
    }
    
    
}